package ar.edu.unlp.info.cdiv.service;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ar.edu.unlp.info.cdiv.model.Persona;

@Service
@Transactional
public class PersonService extends HibernateDaoSupport{
	
	@Autowired
	public PersonService(SessionFactory factory){
		this.setSessionFactory(factory);
	}
	
	public void save(Object object){
		this.getHibernateTemplate().saveOrUpdate(object);
	}
	
	public Object get(Class clazz, Long id){
		return this.getHibernateTemplate().get(clazz, id);
	}
	
	public List getAll(Class clazz){
		return this.getHibernateTemplate().loadAll(clazz);
	}

	public Persona findByUsername(String username) {
		DetachedCriteria cri = DetachedCriteria.forClass(Persona.class);
		cri.add(Property.forName("user.username").eq(username));
		List<Persona> list = (List<Persona>) this.getHibernateTemplate().findByCriteria(cri);
		Persona person = null;
		if (!list.isEmpty()){
			person = list.get(0);
		}
		return person;
	}

}
